package com.sright.bcard.content.biz.manager.impl;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.exceptions.ClientException;
import com.dingtalk.api.response.OapiRobotSendResponse;
import com.sright.bcard.common.biz.manager.ContentCheckManager;
import com.sright.bcard.common.biz.manager.DingTalkManager;
import com.sright.bcard.common.biz.manager.IMailManager;
import com.sright.bcard.common.service.share.dto.content.ApplyDTO;
import com.sright.bcard.common.service.share.dto.content.TryUseMessageDTO;
import com.sright.bcard.common.service.share.dto.user.RegisterDTO;
import com.sright.bcard.common.service.share.enums.SourceTypeEnum;
import com.sright.bcard.common.service.share.exception.base.BusinessErrorException;
import com.sright.bcard.common.service.share.exception.code.BusinessCode;
import com.sright.bcard.common.service.share.utils.DataConvertUtils;
import com.sright.bcard.common.service.share.utils.DateTimeUtils;
import com.sright.bcard.content.biz.manager.MessageManager;
import com.sright.bcard.content.dal.dao.CardUserInfoDAO;
import com.sright.bcard.content.dal.dao.MessageDAO;
import com.sright.bcard.content.dal.entity.CardUserInfoDO;
import com.sright.bcard.common.service.share.dto.content.MessageDTO;
import com.sright.bcard.common.service.share.dto.content.ReferrerDTO;
import com.sright.bcard.content.dal.entity.MessageDO;
import com.sright.bcard.content.share.service.SmsService;
import com.sright.bcard.user.dal.dao.MemberDAO;
import com.sright.bcard.user.dal.dao.VisitorDAO;
import com.sright.bcard.user.dal.entity.MemberDO;
import com.sright.bcard.user.dal.entity.VisitorDO;
import com.sright.bcard.user.share.service.AuthService;
import com.taobao.api.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

@Component
@Slf4j
public class MessageManagerImpl implements MessageManager {

    public static final int CARDLIMIT = 7;
    public static final int MEMBERLIMIT = 3;
    public static final int TRYDAY = 15;

    @Value("${TRY_USE_SMS_TMP_CODE}")
    private String smsTmpCode;

    @Autowired
    private MessageDAO messageDAO;

    @Autowired
    private VisitorDAO visitorDAO;

    @Autowired
    private CardUserInfoDAO cardUserInfoDAO;

    @Autowired
    private MemberDAO memberDAO;

    @Autowired
    private DingTalkManager dingTalkManager;

    @Autowired
    private IMailManager iMailManager;

    @Autowired
    private AuthService authService;

    @Autowired
    private SmsService smsService;

    @Autowired
    private ContentCheckManager contentCheckManager;

    @Override
    public ReferrerDTO referrer(Long memberId) {
        VisitorDO visitorDO = visitorDAO.selectByMmeberIdOrderTime(memberId);
        ReferrerDTO referrerDTO = new ReferrerDTO();
        if (visitorDO != null) {
            CardUserInfoDO cardUserInfoDO = cardUserInfoDAO.selectOneByUserId(visitorDO.getUserId());
            referrerDTO.setName(cardUserInfoDO.getName());
        }
        return referrerDTO;
    }

    @Override
    public ApplyDTO addMessage(MessageDTO messageDTO) throws NoSuchAlgorithmException, ApiException, InvalidKeyException, UnsupportedEncodingException, ClientException, ParseException {
        MessageDO temp = messageDAO.selectByMemberId(messageDTO.getMemberId());
        if(temp != null) {
            if (temp.getIsOpening() == 1) {
                throw new BusinessErrorException(BusinessCode.APPLY_REPEAT);
            }
        }
        //新增敏感词审核
        List<String> contentList = new LinkedList<>();
        if (StringUtils.isNotEmpty(messageDTO.getCompany())) {
            contentList.add(messageDTO.getCompany());
        }
        if (StringUtils.isNotEmpty(messageDTO.getName())) {
            contentList.add(messageDTO.getName());
        }
        if (StringUtils.isNotEmpty(messageDTO.getJob())) {
            contentList.add(messageDTO.getJob());
        }
        if (CollectionUtils.isNotEmpty(contentList)) {
            String checkResult = contentCheckManager.textCheck(contentList,messageDTO.getMemberId(), SourceTypeEnum.APPLET.getValue());
            System.out.println(checkResult);
            if (checkResult.equals("block")) {
                throw new BusinessErrorException(BusinessCode.CONTAIN_SENSITIVE_WORDS);
            }
        }
        // DTO 转 DO
        MessageDO messageDO = new MessageDO();
        DataConvertUtils.convertDTO2DO(messageDTO, messageDO);
        messageDO.setIsOpening(1);
        messageDAO.insertSelective(messageDO);

        RegisterDTO registerDTO = new RegisterDTO();
        registerDTO.setUsername(messageDTO.getMobile());
        registerDTO.setName(messageDTO.getCompany());
        registerDTO.setPassword(messageDTO.getMobile());
        registerDTO.setContacts(messageDTO.getName());
        registerDTO.setMobile(messageDTO.getMobile());
        registerDTO.setDepartment(messageDTO.getJob());
        registerDTO.setJob(messageDTO.getJob());
        registerDTO.setCardNum(MEMBERLIMIT);
        registerDTO.setDays(TRYDAY);

        Date expireAt = DateTimeUtils.formatDate(DateTimeUtils.getAfterDay(TRYDAY),DateTimeUtils.DATE_TIME_STYLE);
        registerDTO.setExpirationAt(expireAt);
        registerDTO.setCardCoverLimit(100);
        registerDTO.setCardLogoLimit(100);
        registerDTO.setCardLogoLimit(100);
        registerDTO.setVideoCoverLimit(100);
        registerDTO.setCorporateVideoLimit(100);
        authService.register(registerDTO);

        MemberDO memberDO = memberDAO.selectById(messageDTO.getMemberId());
        //发送钉钉通知
        sendDingTalkMessage(messageDTO,memberDO.getNickname());
        //给客户发送邮件
        iMailManager.sendHtmlMail(messageDTO.getEmail(),"CuFace企业账号开通成功",emailContent(messageDTO.getCompany(),messageDTO.getMobile(),messageDTO.getName()));

        //短信提醒
        TryUseMessageDTO tryUseMessageDTO = new TryUseMessageDTO();
        tryUseMessageDTO.setPhone(messageDTO.getMobile());
        tryUseMessageDTO.setPassword(messageDTO.getMobile());
        String jsonParam = JSON.toJSONString(tryUseMessageDTO);
        smsService.sendMessage(jsonParam,smsTmpCode,messageDTO.getMobile());

        ApplyDTO applyDTO = new ApplyDTO();
        applyDTO.setMobile(messageDTO.getMobile());
        applyDTO.setPassword(messageDTO.getMobile());
        applyDTO.setCompany(messageDTO.getName());
        applyDTO.setDays(15);
        applyDTO.setExpireDate(DateTimeUtils.formatString(expireAt,DateTimeUtils.DATE_TIME_STYLE));
        return applyDTO;
    }

    @Async
    public OapiRobotSendResponse sendDingTalkMessage(MessageDTO messageDTO,String nickname) throws ApiException, NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException, ApiException, NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException {
        //组装数据
        String content = nickname + "在CuFace小程序开通了企业账号";
        content += "\r姓名：" + messageDTO.getName();
        content += "\r公司：" + messageDTO.getCompany();
        content += "\r职位：" + messageDTO.getJob();
        content += "\r手机：" + messageDTO.getMobile();
        content += "\r邮箱：" + messageDTO.getEmail();
        content += "\r推荐人：" + (messageDTO.getReferrer() == null ? "" : messageDTO.getReferrer());
        content += "\r" + DateTimeUtils.formatString(new Date(),DateTimeUtils.DATE_TIME_STYLE);

        OapiRobotSendResponse response = dingTalkManager.sendGroupMessage(content);
        return response;
    }

    //组装邮件内容
    public String emailContent(String company,String mobile,String contact) {
        String openDate = DateTimeUtils.longTransStringDate(new Date().getTime());
        String content = "<p></p><div class=\"media-wrap image-wrap\"><img src=\"https://ergeng-static.oss-cn-hangzhou.aliyuncs.com/cufacelogo.png\" width=\"100px\" height=\"97px\" style=\"width:100px;height:97px\"/></div><p></p><p><span style=\"color:#333333\"><span style=\"font-size:16px\">" + contact + "，你好：</span></span></p><p><span style=\"color:#333333\"><span style=\"font-size:16px\">" + company + "的CuFace企业版账号已开通。试用体验期15天，可邀请" + MEMBERLIMIT + "名员工，创建" + CARDLIMIT + "个微主页。</span></span></p><p></p><p><span style=\"font-size:16px\"><span style=\"color:#333333\">在浏览器内打开网址</span><span style=\"color:#666666\">（建议用chrome浏览器）</span></span></p><p><span style=\"font-size:16px\"><u><span style=\"color:#2d8cf0\">https://card.console.ergengtv.com</span></u><br/><br/>账号<br/><strong>" + mobile + "</strong><br/><br/>默认密码<span style=\"color:#666666\">（登录后修改）</span><br/><strong>" + mobile + "</strong></span><br/></p><p></p><p><br/><span style=\"color:#666666\"><span style=\"font-size:14px\">如非本人操作，请忽略该邮件。祝使用愉快！</span></span></p><p></p><p><span style=\"color:#666666\"><span style=\"font-size:16px\">视然CuFace开发团队</span></span></p><p><span style=\"color:#666666\"><span style=\"font-size:16px\">" + openDate + "</span></span></p><p><span style=\"color:#666666\"><br/><span style=\"font-size:14px\">这是来自CuFace系统发送的邮件，请勿直接回复。</span></span></p><p></p><p></p><p></p><div class=\"media-wrap image-wrap\"><img src=\"https://ergeng-static.oss-cn-hangzhou.aliyuncs.com/20201009102433.jpg\" width=\"359px\" height=\"160px\" style=\"width:359px;height:160px\"/></div><p><span style=\"font-size:14px\"><span style=\"color:#666666\">企业后台操作手册：</span><span style=\"color:#2d8cf0\"><u>https://shimo.im/docs/vCwYCDDdR3dqQdCD/</u></span></span></p><p></p>";
        return content;
    }
}
